package com.lujieni.springboothutool.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.lujieni.springboothutool.dao.DepartmentDao;
import com.lujieni.springboothutool.po.DepartmentPO;
import com.lujieni.springboothutool.utils.MyTreeUtil;
import com.lujieni.springboothutool.vo.DepartmentResVO;
import com.lujieni.springboothutool.vo.DepartmentTreeVO;
import com.lujieni.springboothutool.vo.Hello;
import com.sun.net.httpserver.Headers;
import com.sun.org.apache.regexp.internal.RE;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/6/2 19:47
 * @Description:
 */
@RestController
@RequiredArgsConstructor
public class TreeController {

    private final DepartmentDao departmentDao;

    /**
     * 利用hutool解析树结构
     *
     * @return
     */
    @GetMapping("/getAll")
    public List<Tree<Integer>> getAll(){
        List<DepartmentPO> data = departmentDao.selectList(null);

        // 1.先将数据转为 List<TreeNode<Integer>>
        List<TreeNode<Integer>> treeNodes = data.stream().map(e -> {
            TreeNode<Integer> treeNode = new TreeNode<>();
            treeNode.setId(e.getId());
            treeNode.setParentId(e.getParentId());
            treeNode.setName(e.getName());
            treeNode.setWeight(e.getSort()); // 越低排序就越靠前

            HashMap<String, Object> map = new HashMap<>();
            map.put("age", 33);
            treeNode.setExtra(map);

            return treeNode;
        }).collect(Collectors.toList());

        // 2. 构建树（0为顶层父ID）
        return TreeUtil.build(treeNodes, 0);
    }

    /**
     *  自己解析树结构(只有2层)
     *
     * @return
     */
    @GetMapping("/getTree")
    public List<DepartmentResVO> getTree(){
        List<DepartmentPO> data = departmentDao.selectList(null);
        List<DepartmentResVO> result = MyTreeUtil.format(data, DepartmentResVO.class, e -> e.getParentId().equals(0));
        return result;
    }

    /**
     * 传枚举值就好,SYSTEM_ADMIN&COMPANY_ADMIN即可
     * @param hello
     */
    @PostMapping("/useEnum")
    public void test(@RequestBody Hello hello){
        System.out.println(hello.getRoleType().getCode());
    }

    /**
     * postman中Authorization一栏可以在header中直接获取
     */
    @PostMapping("/authorization")
    public String authorization(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        return authorization;
    }

}
